<?php
class Admin_AdminLoginController extends Zend_Controller_Action
{
	public function init()
	{
	$this->_helper->getHelper('layout')->setLayout('login');
	}
	public function loginAction()
	{
	$auth=Zend_Auth::getInstance()->getStorage()->read();
	if(Zend_Auth::getInstance()->hasIdentity()){
		$form=new Myblog_Form_Login;
		$this->view->form=$form;
		if($this->getRequest()->isPost() && $form->isValid($this->getRequest()->getPost())){

			$values=$form->getValues();
			$adapter=new Myblog_Auth_Adapter_Doctrine($values['userlogin'],sha1($values['userpass']));
		    $auth=Zend_Auth::getInstance();
		    $result=$auth->authenticate($adapter);
				if($result->isValid()){
						 $auth = Zend_Auth::getInstance();
							$data = $auth->getStorage()->read();
							$storage_data = new stdClass();
							$storage_data->data = $adapter->getResultArray();
                            $storage_data->data[0]['logindatetime'] = date('m/d/Y H:i:s');
							$storage_data->status = $storage_data->data[0]['role'];

                            $admins = new Myblog_Model_Admins;
                            $admins->login = $storage_data->data[0]['userlogin'];
                            $admins->logintime =  $storage_data->data[0]['logindatetime'];
                            $admins->user_id = $storage_data->data[0]['id'];
                            $admins->save();
							$auth->getStorage()->write($storage_data);
							
				$session=new Zend_Session_Namespace('Zend.Auth');
				$session->setExpirationSeconds(60*60);
				$session->user=$adapter->getResultArray('password');
				$session->lock();
				//Zend_Debug::dump(Zend_Session::getSaveHandler());exit;
				//$this->_request->getCookie()
					if(isset($session->requestURL)){
						$url=$session->requestURL;
						unset($session->requestURL);
						$this->_redirect($url);
					}else{
							
							$this->_helper->getHelper('FlashMessenger')
									->addMessage('Вы успешно авторизовались!');
							$this->redirect('/admin/login/success');
							
						}
					}else{
							$this->view->message='Вы не авторизовались,повторите снова';
						 }

			}
		}
		else{
					if($auth->status=='admin'){
						$this->_helper->getHelper('FlashMessenger')
									->addMessage('Вы авторизованы');
							$this->redirect('/admin/login/success');
				 	}else{$this->redirect('/admin/login');}
				}
	}
	public function logoutAction()
	{

    Zend_Session::namespaceUnset('Zend.Auth');
	Zend_Auth::getInstance()->clearIdentity();
    Zend_Session::forgetMe();
    Zend_Session::destroy(true);
	$this->redirect('admin/login');
	}

	public function successAction()
	{
	
		if($this->_helper->getHelper('FlashMessenger')->getMessages())
		{
			$this->_helper->getHelper('layout')->setLayout('admin');
		    $this->view->messages=$this->_helper
			->getHelper('FlashMessenger')
			->getMessages();
            $this->getResponse()->setHeader('Refresh','3; URL=/admin/siteinfo');
		
		}else{
			$this->redirect('/');
			}
	}
}
?>
